package qs.openxt.libs.cv;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.hardware.Camera;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.MediaRecorder;
import android.media.MediaRecorder.OnErrorListener;
import android.media.MediaRecorder.OnInfoListener;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import qs.openxt.libs.App;
import qs.openxt.libs.R;
import qs.openxt.libs.util.Utils;

public class Video extends Activity implements OnClickListener, SurfaceHolder.Callback, SensorEventListener, OnInfoListener, OnErrorListener, OnCheckedChangeListener{
	private String mRecVedioPath = null;

	private SurfaceView mSurfaceView;
	private SurfaceHolder mSurfaceHolder;
	private Button startButton;
	private boolean mIsRecording = false;
	private MediaRecorder mMediaRecorder;
	private TextView timer = null;
	private Camera mCamera = null;
	private String mFilePath = null;
	
	private int hour = 0, minute = 0, second = 0, width = 320, height = 240, bit = 384;
    private SensorManager sm;
    private double index = 0;
    private Timer mTimer = null;
    
    private RadioGroup radioGroup;
    private RadioButton radioButton0, radioButton1, radioButton2;
    private String val = "1";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		//android的屏幕保持常亮
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		
		setContentView(R.layout.activity_camera);

		mRecVedioPath = Utils.getExternalStorageDirectory() + "/" + App.PATH_NAME + "/video";
		File f = new File(mRecVedioPath);
		if (!f.exists()) {
			f.mkdirs();
		}
		
		width = 320; height = 240; bit = (width * height * 3) * 2;

		mSurfaceView = (SurfaceView) findViewById(R.id.arc_hf_video_view);
		timer = (TextView) findViewById(R.id.arc_hf_video_timer);
        timer.setVisibility(View.GONE);
        
        radioGroup = (RadioGroup)findViewById(R.id.radio_group);
        radioGroup.setOnCheckedChangeListener(this);
        radioButton0 = (RadioButton)findViewById(R.id.radio0);
        radioButton1 = (RadioButton)findViewById(R.id.radio0);
        radioButton2 = (RadioButton)findViewById(R.id.radio0);

		startButton = (Button) findViewById(R.id.arc_hf_video_start);
		startButton.setText("开始拍摄");
		startButton.setOnClickListener(this);
		
		sm = (SensorManager) getSystemService(SENSOR_SERVICE);  
        sm.registerListener(this, sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
		
		mSurfaceHolder = mSurfaceView.getHolder();
		mSurfaceHolder.setKeepScreenOn(true);
		mSurfaceHolder.addCallback(this);
		mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		
		//强制横屏
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
	}
	
	
	@Override
	public void onClick(View v) {
		if(v.getId() == R.id.arc_hf_video_start){
			if (mIsRecording == false) {
				if(index > -0.5 && index < 1){
					if(sm != null)
						sm.unregisterListener(this);
					sm = null;
					startmMediaRecorder();
				}else
					Toast.makeText(this, "请把屏幕按逆时针方向旋转90度，在点击拍摄按钮", Toast.LENGTH_LONG).show();
			} else {
				stopmMediaRecorder();
				onBackPressed();
			}
		}
		
	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		mSurfaceHolder = holder;
		
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		mSurfaceHolder = holder;
		if(mCamera != null){
			mCamera.lock();
	        mCamera.release();//加上这句，就OK！
	        mCamera=null;
		}
	}


	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
		mSurfaceHolder = holder;
		
	}

	private void stopmMediaRecorder() {
		timer.setVisibility(View.GONE);
		radioGroup.setVisibility(View.VISIBLE);
		startButton.setText("开始拍摄");
		stopTime();
        timer.setText(format(hour) + ":" + format(minute) + ":" + format(second));
		if (mIsRecording) {
			mMediaRecorder.stop();
			mMediaRecorder.reset();
			mMediaRecorder.release();
			mMediaRecorder = null;
			mIsRecording = false;
		}
		if (mCamera != null) {
			mCamera.lock();
			mCamera.release();
			mCamera = null;
		}
	}

	private void startmMediaRecorder() {
		try{
			if("1".equals(val)){
				width = 320; height = 240; bit = (width * height * 3) * 2;
			}else if("2".equals(val)){
				width = 480; height = 320; bit = (width * height * 3);//bit = 512;
			}else if("3".equals(val)){
				width = 640; height = 480; bit = (width * height * 3) / 2;//bit = 512;
			}
			Toast.makeText(this, "当前视频分辨率" + width + "*" + height + "@比特率:" + bit, Toast.LENGTH_LONG).show();
			
			startButton.setText("停止拍摄");
			second = 0;
	        minute = 0;
	        hour = 0;
			
			mIsRecording = true;
			mMediaRecorder = new MediaRecorder();
			mMediaRecorder.reset();
			if(mCamera != null){
				mCamera.lock();
				mCamera.release();
				mCamera = null;
			}
			mCamera = Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK);
			if (mCamera != null) {
				mCamera.unlock();
			}
			mFilePath = mRecVedioPath + "/" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".mp4";
			
			mMediaRecorder.setCamera(mCamera);
			mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);//设置视频源
			mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);//设置输出格式
			mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);//设置视频编码
			mMediaRecorder.setVideoEncodingBitRate(bit);
			mMediaRecorder.setOutputFile(mFilePath);//设置输出路径
			
			mMediaRecorder.setPreviewDisplay(mSurfaceHolder.getSurface());
			mMediaRecorder.setOnInfoListener(this);
			mMediaRecorder.setOnErrorListener(this);
			
			mMediaRecorder.prepare();
			mMediaRecorder.start();
			
			timer.setVisibility(View.VISIBLE);
			radioGroup.setVisibility(View.GONE);
			startTime();
		}catch(Exception e){
			mIsRecording = false;
			stopmMediaRecorder();
			Toast.makeText(this, "手机不支持视频分辨率" + width + "*" + height + ":" + e.getMessage(), Toast.LENGTH_LONG).show();
		}
	}
	
	private void startTime(){
		stopTime();
		mTimer = new Timer(true);
		mTimer.schedule(new TimerTask() {
			public void run() {
				Message message = new Message();
				message.what = 1;
				handler.sendMessage(message);
			}
		}, 1000, 1000);
	}
	private void stopTime(){
		if(mTimer != null)
			mTimer.cancel();
	}
	
	final Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
                second++;
                if (second >= 60) {
                    minute++;
                    second = second % 60;
                }
                if (minute >= 60) {
                    hour++;
                    minute = minute % 60;
                }
                timer.setText(format(hour) + ":" + format(minute) + ":" + format(second));
				break;
			}
			super.handleMessage(msg);
		}
	};

    /*
     * 格式化时间
     */
    public String format(int i) {
        String s = i + "";
        if (s.length() == 1) {
            s = "0" + s;
        }
        return s;
    }
    
    @Override
	public void onSensorChanged(SensorEvent event) {
		if (Sensor.TYPE_ACCELEROMETER != event.sensor.getType()) {  
            return;  
        }  
     
        float[] values = event.values;  
        float ax = values[0];  
        float ay = values[1];  
     
        double g = Math.sqrt(ax * ax + ay * ay);  
        double cos = ay / g;  
        if (cos > 1) {  
            cos = 1;  
        } else if (cos < -1) {  
            cos = -1;  
        }  
        double rad = Math.acos(cos);
        if (ax < 0) {  
            rad = 2 * Math.PI - rad;  
        }  
     
        int uiRot = getWindowManager().getDefaultDisplay().getRotation();  
        double uiRad = Math.PI / 2 * uiRot;  
        rad -= uiRad;
        index = rad;
	}

	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {
		
	}
	
	/*
     * 覆写返回键监听
     */
    @Override
    public void onBackPressed() {
        if (mMediaRecorder != null)
           stopmMediaRecorder();
        
        if(mFilePath != null){
	        Intent intent = new Intent();
			intent.putExtra("path", mFilePath);
			setResult(RESULT_OK, intent);
        }
        finish();
    }
	
	protected void onDestroy() {
		if(sm != null)
			sm.unregisterListener(this);  
        super.onDestroy();  
    }
	
	@Override
	public void onError(MediaRecorder mr, int what, int extra) {
		switch (what) {
		case MediaRecorder.MEDIA_ERROR_SERVER_DIED:
			break;

		case MediaRecorder.MEDIA_RECORDER_ERROR_UNKNOWN:
			break;
		}
	}

	@Override
	public void onInfo(MediaRecorder mr, int what, int extra) {
		switch (what) {
		case MediaRecorder.MEDIA_RECORDER_INFO_MAX_DURATION_REACHED:
			break;
		case MediaRecorder.MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED:
			break;
		case MediaRecorder.MEDIA_RECORDER_INFO_UNKNOWN:
			break;
		}
	}


	@Override
	public void onCheckedChanged(RadioGroup group, int checkedId) {
		if(radioButton0.getId() == checkedId){
			val = "1";
		}else if(radioButton1.getId() == checkedId){
			val = "2";
		}else if(radioButton2.getId() == checkedId){
			val = "3";
		}
	}
}
